const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { VueLoaderPlugin } = require('vue-loader');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

const isProduction = process.env.NODE_ENV == 'production';

module.exports = () => {
  return {
    entry: {
      index: {
        import: './src/index.js',
        dependOn: 'shared',
      },
      shared: ['vue'],
    },
    devServer: {
      open: true,
      port: 3000,
    },
    output: {
      chunkFilename: isProduction
        ? '[name].[chunkhash:8].chunk.js'
        : '[name].chunk.js',
      filename: isProduction ? '[name].[contenthash:8].js' : '[name].js',
    },
    mode: isProduction ? 'production' : 'development',
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true,
              cacheCompression: false,
            },
          },
        },
        {
          test: /\.vue$/,
          loader: 'vue-loader',
        },
        {
          test: /\.css$/,
          use: [
            isProduction ? MiniCssExtractPlugin.loader : 'vue-style-loader',
            'css-loader',
          ],
        },
        {
          test: /\.less$/,
          use: [
            isProduction ? MiniCssExtractPlugin.loader : 'vue-style-loader',
            'css-loader',
            'less-loader',
          ],
        },
      ],
    },
    resolve: {
      alias: {
        // 使用 esm 的版本，来让 Webpack 更有效地进行 tree-shaking
        vue$: 'vue/dist/vue.runtime.esm-bundler.js',
      },
      extensions: ['.js', '.vue'],
    },
    plugins: [
      new VueLoaderPlugin(),
      new HtmlWebpackPlugin({
        template: 'index.html',
        chunks: ['shared', 'index'],
      }),
      isProduction
        ? new MiniCssExtractPlugin({
            filename: '[name].[contenthash:8].css',
            chunkFilename: '[name].[contenthash:8].chunk.css',
          })
        : null,
      new CleanWebpackPlugin(),
    ].filter(Boolean),
  };
};
